package com.helloniu.red5;

import static org.red5.server.api.ScopeUtils.getScopeService;
import java.io.IOException;
import org.red5.server.api.IScope;
import org.red5.server.api.stream.IStreamService;
import org.red5.server.net.rtmp.event.IRTMPEvent;
import org.red5.server.stream.IBroadcastScope;
import org.red5.server.stream.StreamService;
import org.red5.server.stream.message.RTMPMessage;
import com.helloniu.red5.stream.LiveFLVData;

public class WebHandler extends AbsWebHandler {
    public WebHandler() {
        super();
    
        new Thread(new LiveStreamTest()).start();
    }
    
    // handlers stream
    /**
     * Send the audiodata or videodata to audio&video output stream. 
     */
    public void doStreamRespond(String roomID, String streamID, IRTMPEvent body) {      
        if(getScope() == null) {
            return;
        }

        IScope roomScope = getChildScope(roomID);
        
        Tool.o(getScope());
        
        if(roomScope == null) {
            return;
        }
        
        IBroadcastScope abs = getBroadcastScope(roomScope, streamID);

        // @by tonyy
        if(abs == null) {
            return;
        }
      
        RTMPMessage rtmpmsg  = new RTMPMessage();                         
        rtmpmsg.setBody(body);
      
        try {                   
            abs.pushMessage(rtmpmsg);
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }

    /**
     * Get the stream name scope.
     * 
     * @scope room scope
     * @name stream name
     * ****/
    private IBroadcastScope getBroadcastScope(IScope roomScope, String name) {
        IStreamService service = (IStreamService) getScopeService(roomScope,
                IStreamService.class, StreamService.class);
        
        Tool.o("___getBroadcastScope____1 is : " + roomScope + ", " + service);

        if (!(service instanceof StreamService)) {
            return null;
        
        }

        IBroadcastScope bs = ((StreamService) service).getBroadcastScope(roomScope, name);        
        Tool.o("___getBroadcastScope___2 is : " + bs +"|"+ name);

        return bs;
    }
    
    private class LiveStreamTest extends Thread {
        public void run() {
            while(true) {
                try {                                               
                    IRTMPEvent body = LiveFLVData.getRTMPEvent();
                                         
                    if(body != null) {
                        doStreamRespond("room1234", "stream1234", body);                               
                    }
                } 
                catch(Exception ex) {
                    // do nothing
                    ex.printStackTrace();
                }
            }
        }    
    }
}
